<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserDcoinsLog extends Model
{
    const  REASON_TYPE_SIGN = 1;//赞助
    const  REASON_TYPE_WORKHELP = 2;//作业帮
    const  REASON_TYPE_ALGOTHRIMOUTING = 3;//算法外包
    const  REASON_TYPE_DB2POINTS = 4;//D币转积分
    const  REASON_TYPE_MANMODIFIED = 5;//人为修改
    const  REASON_TYPE_DOWNLOAD_RESOURCE = 6;//下载资源
    const  REASON_TYPE_RESOURCE_DOWNLOADED = 7;//资源被下载
    const  REASON_TYPE_HOMEWORK_MINUS = 8;//做作业帮消耗
    const  REASON_TYPE_HOMEWORK_ADD = 9;//做作业帮增加
    const REASON_TYPE_VIP_ADD = 10; //开通 vip 增加
    //
    const HOMEWORK_MINUS_DCOINS = 5;
    public static function getLatestUDcoinLog($user_id)
    {
        $user_dcoins= UserDcoinsLog::where('user_id', $user_id)
            ->orderBy('updated_at', 'DESC')
            ->first();
        if (empty($user_dcoins)) {
            return null;
        }
        return $user_dcoins;
    }

    /*
     *
     */
    public static function getDcoinLogByPaymentId($payment_id)
    {
        $user_dcoins= UserDcoinsLog::where('yz_payment_id', $payment_id)
            ->first();
        if (empty($user_dcoins)) {
            return null;
        }
        return $user_dcoins;
    }

    public static function dcoinStatistic($user_id)
    {
        $cur_dcoin_item = UserDcoinsLog::getLatestUDcoinLog($user_id);
        $res['remain_dcoins'] = 0;
        $res['add_dcoins'] = 0;
        $res['minus_dcoins'] = 0;
        //当前积分数
        if (!empty($cur_dcoin_item) && !empty($cur_dcoin_item['remain_dcoins'])) {
            $res['remain_dcoins'] = $cur_dcoin_item['remain_dcoins'];
        }
        //增加的积分数
        $user_dcoins_add = UserDcoinsLog::where('user_id', $user_id)
            ->where('type', 1)
            ->sum('dcoins');
        if (!empty($user_dcoins_add)) {
            $res['add_dcoins'] = $user_dcoins_add;
        }
        //消耗的积分数
        $user_dcoins_minus = UserDcoinsLog::where('user_id', $user_id)
            ->where('type', 2)
            ->sum('dcoins');
        if (!empty($user_dcoins_minus)) {
            $res['minus_dcoins'] = $user_dcoins_minus;
        }

        return $res;
    }

    public static function userDcoinList($user_id, $limit = 20)
    {
        //取最前面的10条
        $user_dcoin_list = UserDcoinsLog::where('user_id', $user_id)
            ->orderBy('updated_at', 'DESC')
            ->paginate($limit);
        return $user_dcoin_list;
    }

    /*
     * 关联模型
     */
    public function user()
    {
        return $this->belongsTo('App\\Models\\User');
    }
}
